import { defineStore, acceptHMRUpdate } from 'pinia'
import { request, ListData, TemplateData } from '@/service/request'

export interface TemplatesProps {
  templates: TemplateData[]
  totalTemplates: number
  works: TemplateData[]
  totalWorks: number
}

export const useTemplatesStore = defineStore('templates', {
  state: (): TemplatesProps => ({
    templates: [],
    totalTemplates: 0,
    works: [],
    totalWorks: 0
  }),

  getters: {
    getTemplateById: state => (id: number) => {
      return state.templates.find(item => item.id === id)
    }
  },

  actions: {
    async fetchTemplates(payload: any) {
      const rawData = await request<ListData<TemplateData>>('/templates', 'get', payload, 'fetchTemplates')
      const { list, count } = rawData.data
      this.templates = [...this.templates, ...list]
      this.totalTemplates = count
    },

    async fetchTemplate(workId: string) {
      const rawData = await request<TemplateData>(`/templates/${workId}`, 'get')
      this.templates = [rawData.data]
    },

    async fetchWorks(payload: any) {
      const rawData = await request<ListData<TemplateData>>('/works', 'get', payload, 'fetchWorks')
      const { list, count } = rawData.data
      this.works = list
      this.totalWorks = count
    },

    async deleteWork(workId: number) {
      await request(`/works/${workId}`, 'delete')
      this.works = this.works.filter(work => work.id !== workId)
    }
  }
})

if (import.meta.hot) {
  import.meta.hot.accept(acceptHMRUpdate(useTemplatesStore, import.meta.hot))
}
